import {
  delete_platformuser,
  edit_platformuser_status,
  platformuser_list,
  platform_doctor_bind_application_list,
} from '@/services/platformuser';
import age from '@/utils/age';
import paging_fun from '@/utils/paging';
import { InfoCircleTwoTone, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Divider, message, Modal, QRCode, Switch, Tabs, Tag } from 'antd';
import { useRef, useState } from 'react';
import AddStaff from './components/AddStaff';
import Agree from './components/Agree';
import Check from './components/Check';
import EditStaff from './components/EditStaff';
import Refuse from './components/Refuse';
import SetRole from './components/SetRole';
import ImportDoctor from './components/ImportDoctor';

type GithubIssueItem = {
  birth: string;
  id: number;
  username: string;
  sex: string;
  create_time: string;
  manage_name: string;
  department_name: string;
  positional_name: string;
  created_at: string;
  invite_code: string;
  status: number;
  operation_status: number;
  unique_code: string;
  reason: string;
};
const StaffManagement = () => {
  const actionRef = useRef<ActionType>();
  const actionRef2 = useRef<ActionType>();
  // 存储当前id
  const [id, setId] = useState<number>();
  // 控制新建员工模态框的状态
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  // 查看邀请码状态
  const [imageplay, setimageplay] = useState('');
  const [codeVisible, setcodeVisible] = useState(false);
  // 设置角色模态框状态
  const [isRoleModalOpen, setIsRoleModalOpen] = useState(false);
  // 编辑员工模态框状态
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  // 删除员工模态框状态
  const [delVisible, setDelVisible] = useState(false);
  // 查看绑定模态框状态
  const [isCheckModalOpen, setIsCheckModalOpen] = useState(false);
  const [status, setStatus] = useState<number>(0);
  // 同意绑定模态框状态
  const [isAgreeModalOpen, setIsAgreeModalOpen] = useState(false);
  // 拒绝绑定模态框状态
  const [isRefuseModalOpen, setIsRefuseModalOpen] = useState(false);
  // 导入医生模态框状态
  const [importDoctor, setImportDoctor] = useState(false)
  // 控制新建员工模态框显示和隐藏
  const isShowAddModal = (show: boolean) => {
    setIsAddModalOpen(show);
  };
  // 控制设置角色模态框显示和隐藏
  const isShowSetRoleModal = (show: boolean) => {
    setIsRoleModalOpen(show);
  };
  // 控制编辑员工模态框显示和隐藏
  const isShowEditModal = (show: boolean) => {
    setIsEditModalOpen(show);
  };
  // 控制查看绑定模态框的显示喝隐藏
  const isShowCheckModal = (status: boolean) => {
    setIsCheckModalOpen(status);
  };
  // 控制同意绑定模态框的显示喝隐藏
  const isShowAgreeModal = (status: boolean) => {
    setIsAgreeModalOpen(status);
  };
  // 控制拒绝绑定模态框的显示和隐藏
  const isShowRefuseModal = (status: boolean) => {
    setIsRefuseModalOpen(status);
  };
  // 控制导入医生模态框的显示与隐藏
  const isShowImportDoctorModal = (status: boolean) => {
    setImportDoctor(status)
  }
  // 获取员工列表
  const get_platformuser_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
    };
    let res = await platformuser_list(request_body);
    console.log('员工列表', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 获取审批列表
  const get_platform_doctor_bind_application_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
    };
    let res = await platform_doctor_bind_application_list(request_body);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 邀请码
  const isShowEdit = (status: boolean, unique_code: string, invite_code: string) => {
    // console.log(url);
    let url = `http://app_download.limaoniao.com.cn?unique_code=${unique_code}&invite_code=${invite_code}`;
    setimageplay(url);
    setcodeVisible(status);
  };
  // 删除
  const isShowDelVisible = (status: boolean) => {
    setDelVisible(status);
    // seteditId(editId);
  };
  // 删除确认的回调
  const delOk = async () => {
    let request_body = {
      id,
    };
    const res: any = await delete_platformuser(request_body);
    if (res.code == 200) {
      message.success('删除成功');
      actionRef.current?.reload();
      paging_fun(actionRef);
    } else {
      message.success(res.msg);
    }
    setDelVisible(false);
  };
  // 启用/禁用员工
  const edit_memberstatus = async (id: number, status: boolean) => {
    let request_body = {
      id,
      status: status ? 1 : 0,
    };
    const res: any = await edit_platformuser_status(request_body);
    if (res.msg == 'ok') {
      if (status) {
        message.success('员工启用成功！');
      } else {
        message.success('员工禁用成功！');
      }
      actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };
  // 切换Tabs时，刷新
  const changeTab = (e: any) => {
    // console.log('eee', e);
    if (e == '员工管理') {
      actionRef.current?.reload();
    } else if (e == '绑定审批') {
      actionRef2.current?.reload();
    }
  };
  // 员工管理列表字段
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'username',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '性别',
      hideInSearch: true,
      dataIndex: 'sex',
      align: 'center',
      valueEnum: {
        0: {
          text: '未知',
        },
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '年龄',
      hideInSearch: true,
      dataIndex: 'birth',
      align: 'center',
      render: (_, record) => {
        return age(record.birth);
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      align: 'center',
    },
    {
      title: '员工姓名',
      dataIndex: 'username',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '所属科室',
      hideInSearch: true,
      dataIndex: 'department_name',
      align: 'center',
    },
    {
      title: '职称',
      hideInSearch: true,
      dataIndex: 'positional_name',
      align: 'center',
    },
    {
      title: '创建人',
      hideInSearch: true,
      dataIndex: 'manage_name',
      align: 'center',
    },
    {
      title: '创建时间',
      hideInSearch: true,
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
        },
        1: {
          text: '启用',
        },
      },
      render: (_: any, record: { status: number; id: number; operation_status: number }) => (
        <Switch
          disabled={record.operation_status == 0}
          key={record.status === 1}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.status == 1}
          onChange={(event: boolean) => {
            edit_memberstatus(record.id, event);
          }}
        />
      ),
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      valueType: 'option',
      render: (
        _: any,
        record: {
          invite_code: string;
          id: number;
          operation_status: number;
          unique_code: string;
          status: number;
        },
      ) => (
        <>
          {record.operation_status === 0 ? (
            <div style={{ color: 'rgba(0,0,0,0.25)' }}>该账户已被禁用</div>
          ) : (
            <>
              <Button
                key="code"
                type="link"
                size="small"
                onClick={() => {
                  isShowEdit(true, record.unique_code, record.invite_code);
                }}
              >
                邀请码
              </Button>
              <Button
                key="Role"
                type="link"
                size="small"
                onClick={() => {
                  setId(record.id);
                  isShowSetRoleModal(true);
                }}
              >
                设置角色
              </Button>
              <Button
                key="Editor"
                type="link"
                size="small"
                onClick={() => {
                  setId(record.id);
                  isShowEditModal(true);
                }}
              >
                编辑
              </Button>
              <Button
                key="Del"
                type="link"
                size="small"
                onClick={() => {
                  setId(record.id);
                  isShowDelVisible(true);
                }}
                disabled={record.status === 1}
              >
                删除
              </Button>
            </>
          )}
        </>
      ),
    },
  ];
  // 绑定审批列表字段
  const columns2: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'username',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '性别',
      hideInSearch: true,
      dataIndex: 'sex',
      align: 'center',
      valueEnum: {
        0: {
          text: '未知',
        },
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '年龄',
      hideInSearch: true,
      dataIndex: 'birth',
      align: 'center',
      render: (_, record) => {
        return age(record.birth);
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      align: 'center',
    },
    {
      title: '申请人姓名',
      dataIndex: 'username',
      hideInTable: true,
    },
    {
      title: '机构名称',
      hideInSearch: true,
      dataIndex: 'platform_name',
      align: 'center',
    },
    {
      title: '职称',
      hideInSearch: true,
      dataIndex: 'positional_name',
      align: 'center',
    },
    {
      title: '申请原因',
      hideInSearch: true,
      dataIndex: 'reason',
      align: 'center',
      render: (_, record) =>
        record.reason.length >= 5 ? record.reason.substring(0, 5) + '...' : record.reason,
    },
    {
      title: '申请时间',
      hideInSearch: true,
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      valueEnum: {
        0: {
          text: '待审批',
        },
        1: {
          text: '已同意',
        },
        2: {
          text: '已拒绝',
        },
      },
      render: (_: any, record) => (
        <>
          {record.status === 0 ? <Tag color="orange">待审批</Tag> : <></>}
          {record.status === 1 ? <Tag color="green">已同意</Tag> : <></>}
          {record.status === 2 ? <Tag color="red">已拒绝</Tag> : <></>}
        </>
      ),
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      valueType: 'option',
      render: (_: any, record) => (
        <>
          <Button
            key="check"
            type="link"
            size="small"
            onClick={() => {
              setStatus(record.status);
              setId(record.id);
              isShowCheckModal(true);
            }}
          >
            查看
          </Button>
          {record.status === 0 ? (
            <>
              <Button
                key="agree"
                type="link"
                size="small"
                onClick={() => {
                  setId(record.id);
                  isShowAgreeModal(true);
                }}
              >
                同意
              </Button>
              <Button
                key="refuse"
                type="link"
                size="small"
                onClick={() => {
                  setId(record.id);
                  isShowRefuseModal(true);
                }}
              >
                拒绝
              </Button>
            </>
          ) : (
            <></>
          )}
        </>
      ),
    },
  ];
  return (
    <PageContainer breadcrumb={false}>
      <Tabs
        defaultActiveKey="员工管理"
        onChange={changeTab}
        items={[
          {
            key: '员工管理',
            label: '员工管理',
            children: (
              <ProTable
                columns={columns}
                actionRef={actionRef}
                request={async (params = {}, sort, filter) => get_platformuser_list(params)}
                rowKey={(record) => record.id}
                search={{
                  labelWidth: 'auto',
                  collapseRender: false,
                  collapsed: false,
                  span: 6,
                }}
                pagination={{
                  pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="员工列表"
                toolBarRender={() => [
                  <Button
                    key="button"
                    icon={<PlusOutlined />}
                    type="primary"
                    onClick={() => isShowAddModal(true)}
                  >
                    新建
                  </Button>,
                  <Button
                    key="import"
                    type="primary"
                  onClick={() => isShowImportDoctorModal(true)}
                  >
                    导入员工
                  </Button>,
                ]}
              />
            ),
          },
          {
            key: '绑定审批',
            label: '绑定审批',
            children: (
              <ProTable
                columns={columns2}
                actionRef={actionRef2}
                request={async (params = {}, sort, filter) =>
                  get_platform_doctor_bind_application_list(params)
                }
                rowKey={(record) => record.id}
                search={{
                  labelWidth: 'auto',
                  collapseRender: false,
                  collapsed: false,
                  span: 6,
                }}
                pagination={{
                  pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="审批列表"
              />
            ),
          },
        ]}
      />
      {/* 新建员工 */}
      {isAddModalOpen ? (
        <AddStaff
          isAddModalOpen={isAddModalOpen}
          isShowAddModal={isShowAddModal}
          actionRef={actionRef}
        ></AddStaff>
      ) : (
        ''
      )}

      {/* 查看邀请码 */}
      <Modal
        width={400}
        centered
        open={codeVisible}
        onCancel={() => setcodeVisible(false)}
        destroyOnClose={true}
        footer={null}
        closable={true}
        maskClosable={false}
      >
        <div style={{ width: '300px', overflow: 'hidden', margin: '0 auto' }}>
          <QRCode value={imageplay} size={300} />
        </div>
      </Modal>
      {/* 设置角色 */}
      {isRoleModalOpen ? (
        <SetRole
          isRoleModalOpen={isRoleModalOpen}
          isShowSetRoleModal={isShowSetRoleModal}
          id={id}
          actionRef={actionRef}
        ></SetRole>
      ) : (
        ''
      )}
      {/* 编辑员工 */}
      {isEditModalOpen ? (
        <EditStaff
          isEditModalOpen={isEditModalOpen}
          isShowEditModal={isShowEditModal}
          id={id}
          actionRef={actionRef}
        ></EditStaff>
      ) : (
        ''
      )}
      {/* 删除员工 */}
      <Modal
        title="删除确认"
        open={delVisible}
        onOk={delOk}
        onCancel={() => isShowDelVisible(false)}
      >
        <Divider />
        <p>
          <InfoCircleTwoTone twoToneColor="#ffcc00" /> 员工信息删除后无法恢复，确定要删除吗？
        </p>
      </Modal>
      {/* 绑定审批查看 */}
      {isCheckModalOpen ? (
        <Check
          isShowCheckModal={isShowCheckModal}
          isCheckModalOpen={isCheckModalOpen}
          status={status}
          id={id}
        ></Check>
      ) : (
        ''
      )}
      {/* 绑定审批同意 */}
      {isAgreeModalOpen ? (
        <Agree
          isShowAgreeModal={isShowAgreeModal}
          isAgreeModalOpen={isAgreeModalOpen}
          actionRef2={actionRef2}
          id={id}
        ></Agree>
      ) : (
        ''
      )}
      {/* 绑定审批拒绝 */}
      {isRefuseModalOpen ? (
        <Refuse
          isRefuseModalOpen={isRefuseModalOpen}
          isShowRefuseModal={isShowRefuseModal}
          actionRef2={actionRef2}
          id={id}
        ></Refuse>
      ) : (
        ''
      )}
      {/* 导入医生 */}
      {importDoctor ? (
        <ImportDoctor
        importDoctor={importDoctor}
          isShowImportDoctorModal={isShowImportDoctorModal}
          actionRef={actionRef}
        ></ImportDoctor>
      ) : (
        ''
      )}
    </PageContainer>
  );
};
export default StaffManagement;
